package com.laxcen.smoke.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.iot.model.v20180120.PubRequest;
import com.aliyuncs.iot.model.v20180120.PubResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laxcen.smoke.config.CommonEnum;
import com.laxcen.smoke.dao.IntelligentMonitorDao;
import com.laxcen.smoke.dto.res.AddBoxExtraRes;
import com.laxcen.smoke.dto.res.SmartBoardDetailRes;
import com.laxcen.smoke.dto.res.SmartDetailRes;
import com.laxcen.smoke.dto.res.SmartRes;
import com.laxcen.smoke.entity.Smart;
import com.laxcen.smoke.entity.SmartBoard;
import com.laxcen.smoke.entity.SmartBox;
import com.laxcen.smoke.service.IntelligentMonitorService;
import com.laxcen.smoke.util.DBUtils;
import com.laxcen.smoke.util.IdUtils;
import com.laxcen.smoke.util.Response;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

@Service
public class IntelligentMonitorServiceImpl implements IntelligentMonitorService {

    @Autowired
    private IntelligentMonitorDao intelligentMonitorDao;

    @Value("${accessKey}")
    private String accessKey;

    @Value("${accessSecret}")
    private String accessSecret;

    @Value("${productkey}")
    private String productkey;

    @Override
    public Response<Smart> insert(String smartno,String device, BigDecimal lat, BigDecimal lng, String address,String remark) {
        Smart smartbyno = intelligentMonitorDao.getSmartByNo(smartno);
        if (smartbyno!=null){
            return new Response<>(CommonEnum.ZHINENGKUI_IS_EXIST);
        }
        Date date = new Date();
        //添加到smart表
        long idsmart = DBUtils.nextId();
        String smartid = String.valueOf(idsmart);
        intelligentMonitorDao.insert(smartid,smartno,device,lat,lng,address,1,date,remark,"123456",new Date());
       //自动添加一个离线异常
        long idsmartabnor = DBUtils.nextId();
        String smartidabnor = String.valueOf(idsmartabnor);
        intelligentMonitorDao.insertAbnor(smartidabnor,smartno,6,new Date(),1);
        //订阅到iot添加智能柜
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PubRequest request = new PubRequest();
        request.setProductKey(productkey);
        String param = "{\"params\":{\"Id\":\""+smartid+"\",\"DeviceNo\":\""+smartno+"\",\"Lat\":"+lat+",\"Lng\":"+lng+",\"Address\":\""+address+"\",\"Remark\":\""+remark+"\",\"DeviceName\":\""+device+"\"},\"method\":\"thing.event.AddSmart.post\"}";
        request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
        request.setTopicFullName("/sys/"+productkey+"/"+smartno+"/thing/event/AddSmart/post");
        try
        {
            PubResponse response = client.getAcsResponse(request);
            if (response.getSuccess()==false){
                return new Response(CommonEnum.EVENT_PUB_FAIL);
            }

        }
        catch (ServerException e)
        {
            e.printStackTrace();
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }
        long idsmartbo = DBUtils.nextId();
        String smartboid = String.valueOf(idsmartbo);
        intelligentMonitorDao.insertsmartbo(smartboid,0,"A",1,100,1,date,"自动添加");
        //订阅到iot添加自动生成的一个实体柜(主)
        IClientProfile profiles = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient clients = new DefaultAcsClient(profiles);
        PubRequest requests = new PubRequest();
        request.setProductKey(productkey);
        String params = "{\"params\":{\"Id\":\""+smartboid+"\",\"SmartId\":\""+smartid+"\",\"BoardNo\":\"A\",\"Specification\":0,\"Remark\":\""+remark+"\"},\"method\":\"thing.event.AddBoard.post\"}";
        requests.setMessageContent(Base64.encodeBase64String(params.getBytes()));
        requests.setTopicFullName("/sys/"+productkey+"/"+smartno+"/thing/event/AddBoard/post");
        try
        {
            PubResponse response = clients.getAcsResponse(request);
            if (response.getSuccess()==false){
                return new Response(CommonEnum.EVENT_PUB_FAIL);
            }

        }
        catch (ServerException e)
        {
            e.printStackTrace();
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }
        long idsmartboands = DBUtils.nextId();
        String smartboandsid = String.valueOf(idsmartboands);
        intelligentMonitorDao.insertrealsmartandsboard(smartboandsid,IdUtils.getZandS(),smartid,smartboid,date);
        Smart smart = intelligentMonitorDao.getSmartById(smartid);
        Response<Smart> response = new Response();
        response.setData(smart);
        response.setOK();
        return response;
    }

    @Override
    public Response<SmartBoard> addReal(String smartid,String boardno,Integer specification, String remark) {
       String devicename = intelligentMonitorDao.getSmartBySmartid(smartid);
        long ids = DBUtils.nextId();
        String id = String.valueOf(ids);
        Date date = new Date();
        String smartno = intelligentMonitorDao.getSmartBySmartid(smartid);
        List<String> smboardno = intelligentMonitorDao.getBoardno(1,smartno);
        for (int i = 0; i < smboardno.size();i++){
            if (smboardno.get(i).equals(boardno)){
                return new Response<>(CommonEnum.BOARDNO_IS_EXIST);
            }
        }
        intelligentMonitorDao.insertsmartbo(id,specification,boardno,1,100,0,date,remark);
        //添加实体柜信息订阅到iot
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PubRequest request = new PubRequest();
        request.setProductKey(productkey);
        String param = "{\"params\":{\"Id\":\""+id+"\",\"SmartId\":\""+smartid+"\",\"BoardNo\":\""+boardno+"\",\"Specification\":"+specification+",\"Remark\":\""+remark+"\"},\"method\":\"thing.event.AddBoard.post\"}";
        request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
        request.setTopicFullName("/sys/"+productkey+"/"+devicename+"/thing/event/AddBoard/post");
        try
        {
            PubResponse response = client.getAcsResponse(request);
            if (response.getSuccess()==false){
                return new Response(CommonEnum.EVENT_PUB_FAIL);
            }

        }
        catch (ServerException e)
        {
            e.printStackTrace();
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }
        long idss = DBUtils.nextId();
        String idsss = String.valueOf(idss);
        intelligentMonitorDao.insertrealsmartandsboard(idsss,IdUtils.getNewZandS(),smartid,id,date);
        SmartBoard smartBoard = intelligentMonitorDao.getSmartBoardById(id);
        Response<SmartBoard> response = new Response<>();
        response.setOK();
        response.setData(smartBoard);
        return response;
    }

    @Override
    public Response updateReal(String boardid, String boardno, Integer specification, String remark) {
        String devicename = intelligentMonitorDao.getSmartByBoardid(boardid);
        List<String> smboardno = intelligentMonitorDao.getBoardno(1,devicename);
        for (int i = 0; i < smboardno.size();i++){
            if (smboardno.get(i).equals(boardno)){
                String smartboardno = intelligentMonitorDao.getsmartboardno(boardid);
                if (!smartboardno.equals(boardno)) {
                    return new Response<>(CommonEnum.BOARDNO_IS_EXIST);
                }
            }
        }
        intelligentMonitorDao.updatesmbod(boardid,specification,boardno,remark);
        //修改实体柜信息订阅到iot
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PubRequest request = new PubRequest();
        request.setProductKey(productkey);
        String param = "{\"params\":{\"Id\":\""+boardid+"\",\"BoardNo\":\""+boardno+"\",\"Specification\":"+specification+",\"Remark\":\""+remark+"\"},\"method\":\"thing.event.UpdateBoard.post\"}";
        request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
        request.setTopicFullName("/sys/"+productkey+"/"+devicename+"/thing/event/UpdateBoard/post");
        try
        {
            PubResponse response = client.getAcsResponse(request);
            if (response.getSuccess()==false){
                return new Response(CommonEnum.EVENT_PUB_FAIL);
            }

        }
        catch (ServerException e)
        {
            e.printStackTrace();
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response<Smart> update(String id, String no, String device, BigDecimal lat, BigDecimal lng, String address, String remark) {

        //获取已存在的智能柜编号
        List<String> smartexist = intelligentMonitorDao.getSmartNoList(intelligentMonitorDao.getSmartBySmartid(id));
        //获取正确的智能柜编号
//        Smart smartbyno = intelligentMonitorDao.getSmartByNo(no);
////        for (int i = 0; i < smartexist.size();i++){
////            if (smartexist.get(i).equals(smartno)){
////                smartexist.remove(i);
////            }
////        }
        if (smartexist.contains(no)){
            return new Response<>(CommonEnum.ZHINENGKUI_IS_EXIST);
        }

        intelligentMonitorDao.update(id,no,device,lat, lng, address,remark);
        String devicename = intelligentMonitorDao.getSmartBySmartid(id);
//        int row = intelligentMonitorDao.updatesmbod(id,remark);
        //修改智能柜信息订阅到iot
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PubRequest request = new PubRequest();
        request.setProductKey(productkey);
        String param = "{\"params\":{\"Id\":\""+id+"\",\"DeviceNo\":\""+no+"\",\"Lat\":"+lat+",\"Lng\":"+lng+",\"Address\":\""+address+"\",\"Remark\":\""+remark+"\",\"DeviceName\":\""+device+"\"},\"method\":\"thing.event.UpdateSmart.post\"}";
        request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
        request.setTopicFullName("/sys/"+productkey+"/"+devicename+"/thing/event/UpdateSmart/post");
        try
        {
            PubResponse response = client.getAcsResponse(request);
            if (response.getSuccess()==false){
                return new Response(CommonEnum.EVENT_PUB_FAIL);
            }

        }
        catch (ServerException e)
        {
            e.printStackTrace();
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }
        Smart smart = intelligentMonitorDao.getSmartById(id);
        Response response = new Response();
        response.setData(smart);
        response.setOK();
        return response;
    }

    @Override
    public Response<PageInfo<SmartRes>> getByTabList(String searchtext, int roleflag, String province, String city, String area, int pageNo, int pageSize){
        List<SmartRes> list = new LinkedList<>();
        if (roleflag==0) {
            List<SmartRes> listall = intelligentMonitorDao.getAllListByTab(searchtext);
            for (int i = 0; i < listall.size();i++){
                list.add(i,listall.get(i));
            }
        }else if (roleflag==1){
            String place = null;
            if (!province.isEmpty()){
                place = province;
            }
            if (!city.isEmpty()){
                place =place+"/"+ city;
            }
            if (!area.isEmpty()){
                place = place+"/"+area;
            }
            if (searchtext.isEmpty()){
                searchtext=place;
            }
            List<SmartRes> listall = intelligentMonitorDao.getAllListByTabRole(searchtext,place);
            for (int i = 0; i < listall.size();i++){
                list.add(i,listall.get(i));
            }
        }
        Page page = PageHelper.startPage(pageNo, pageSize);
        Response<PageInfo<SmartRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(list);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<PageInfo<SmartRes>> getAllList(int pageNo, int pageSize, int roleflag, String province, String city, String area) {
//        //        获取已经存在的智能柜编号
//        List<String> abNormalRecord = intelligentMonitorDao.getAbn();
//        for (int i = 0; i < abNormalRecord.size();i++) {
//            //TODO 查询主副柜、格子表是否有异常
//            List<String> list = intelligentMonitorDao.getNotState(abNormalRecord.get(i), 3);
//            if (list.size() == 0) {
//                //修改智能柜表状态信息
////                intelligentMonitorDao.updateSmartByNo(0, abNormalRecord.get(i));
//                //修改主柜状态信息
////                intelligentMonitorDao.updateSmartBoardByNo(0,abNormalRecord.get(i));
//                List<String> idlist = intelligentMonitorDao.getIdBySmartno(abNormalRecord.get(i),3);
//                for (int j = 0; j < idlist.size(); j++) {
//                    //修改实体柜表状态信息
//                    intelligentMonitorDao.updatesmartBoardBy(0, abNormalRecord.get(i), idlist.get(j));
//                }
//            }
//        }
        List<SmartRes> reallist = new LinkedList<>();

        if (roleflag==0) {
            List<SmartRes> listall  = intelligentMonitorDao.getAllList();
            for (int i = 0; i < listall.size();i++){
                reallist.add(i,listall.get(i));
            }
        }else if (roleflag==1){
            String place = null;
            if (!province.isEmpty()){
                place = province;
            }
            if (!city.isEmpty()){
                place =place+"/"+ city;
            }
            if (!area.isEmpty()){
                place = place+"/"+area;
            }
            List<SmartRes> listall  = intelligentMonitorDao.getAllListByRole(place);
            for (int i = 0; i < listall.size();i++){
                reallist.add(i,listall.get(i));
            }
        }
        Page page = PageHelper.startPage(pageNo, pageSize);
        Response<PageInfo<SmartRes>> response = new Response<>();
        PageInfo pageInfo = page.toPageInfo();
        pageInfo.setList(reallist);
        response.setOK();
        response.setData(pageInfo);
        return response;
    }

    @Override
    public Response<List<SmartDetailRes>> getByOneList(String id) {

        List<SmartDetailRes> result  = new LinkedList<>();
        SmartDetailRes smartDetailRes = new SmartDetailRes();
//        String sboid = intelligentMonitorDao.getboardid(id);
        List<SmartRes> smartres = intelligentMonitorDao.getByOneIdList(id);
        List<SmartBoard> smartBoard = intelligentMonitorDao.getSMBORDList(id);
//        List<SmartBoard> smartbox = intelligentMonitorDao.getSmartBoxList(sboid);
        for (int i = 0;i<smartres.size();i++){
            smartDetailRes.setAiresult(smartres);
        }
        for (int j = 0;j<smartBoard.size();j++){
            smartDetailRes.setRealresult(smartBoard);
        }
        result.add(smartDetailRes);
        Response<List<SmartDetailRes>> response = new Response<>();
        response.setData(result);
        response.setOK();
        return response;
    }

    @Override
    public Response<List<SmartBoardDetailRes>> getBoardByOneList(String id) {
        List<SmartBoardDetailRes> list = new LinkedList<>();
        SmartBoardDetailRes smartBoardDetailRes = new SmartBoardDetailRes();
        List<SmartBoard> board = intelligentMonitorDao.getSBDList(id);
        List<SmartBox> box = intelligentMonitorDao.getSmartBoxList(id);
        for (int i = 0;i<board.size();i++){
            smartBoardDetailRes.setRealresult(board);
        }
        for (int j = 0;j<box.size();j++){
            smartBoardDetailRes.setBoxresult(box);
        }
        list.add(smartBoardDetailRes);
        Response<List<SmartBoardDetailRes>> response = new Response<>();
        response.setOK();
        response.setData(list);
        return response;
    }

    @Override
    public Response addbox(String id, Integer number,String remark) {
        String devicename = intelligentMonitorDao.getSmartByBoardid(id);
//        String boardid = intelligentMonitorDao.getboardid(id);
//        List<String> list = intelligentMonitorDao.getBoxIsNotNull(id);
//        //判断格子存在报错，不存在再添加格子
//        if (list.size()!=0){
//            return new Response(CommonEnum.BOX_IS_EXIST);
//        }else {
            List<AddBoxExtraRes> addextrabox = intelligentMonitorDao.getFboardNum(1, intelligentMonitorDao.getSmartNoByBoardid(id));
            for (int i = 1; i <= number; i++) {
                String sno = "";
//            if (i<10){
//                sno = String.valueOf(i);
//                sno = "0"+sno;
//            }else{
                int adnum = 8;
                if (addextrabox.size()==0){
                    sno = String.valueOf(i);
                }else {
                for (int j = 1; j <= addextrabox.size();j++){
//                    if (addextrabox.get(j).getBoxno().equals(String.valueOf(adnum))){
                        sno = String.valueOf(number*(addextrabox.size()/adnum)+i);
//                    }
                }

            }

                long smboxid = DBUtils.nextId();
                String idsmbox = String.valueOf(smboxid);
                intelligentMonitorDao.insertsmartbox(idsmbox, sno, 1, new Date(), remark);
                //添加格子订阅到iot
                IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
                DefaultAcsClient client = new DefaultAcsClient(profile);
                PubRequest request = new PubRequest();
                request.setProductKey(productkey);
                String param = "{\"params\":{\"Id\":\"" + idsmbox + "\",\"BoardId\":\"" + id + "\",\"BoxNo\":\"" + sno + "\",\"Remark\":\"" + remark + "\"},\"method\":\"thing.event.AddBox.post\"}";
                request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
                request.setTopicFullName("/sys/" + productkey + "/" + devicename + "/thing/event/AddBox/post");
                try {
                    PubResponse response = client.getAcsResponse(request);
                    if (response.getSuccess() == false) {
                        return new Response(CommonEnum.EVENT_PUB_FAIL);
                    }

                } catch (ServerException e) {
                    e.printStackTrace();
                } catch (ClientException e) {
                    e.printStackTrace();
                }
                long rssid = DBUtils.nextId();
                String idrss = String.valueOf(rssid);
                intelligentMonitorDao.insertrealboandbox(idrss, IdUtils.getZandS(), id, idsmbox, new Date());
            }
//        }

        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response delete(String id) {
        String devicename = intelligentMonitorDao.getSmartBySmartid(id);
        //解绑
        intelligentMonitorDao.delete(id);
        //删除智能柜
        intelligentMonitorDao.deleteSmart(id);
        //删除智能柜信息订阅到iot
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PubRequest request = new PubRequest();
        request.setProductKey(productkey);
        String param = "{\"params\":{\"Id\":\""+id+"\"},\"method\":\"thing.event.DeleteSmart.post\"}";
        request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
        request.setTopicFullName("/sys/"+productkey+"/"+devicename+"/thing/event/DeleteSmart/post");
        try
        {
            PubResponse response = client.getAcsResponse(request);
            if (response.getSuccess()==false){
                return new Response(CommonEnum.EVENT_PUB_FAIL);
            }

        }
        catch (ServerException e)
        {
            e.printStackTrace();
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response deleteBoard(String id) {
        String devicename = intelligentMonitorDao.getSmartByBoardid(id);
        intelligentMonitorDao.deleteBoardone(id);
        intelligentMonitorDao.deleteBoardtwo(id);
        intelligentMonitorDao.deletesmbod(id);
        //删除实体柜信息订阅到iot
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PubRequest request = new PubRequest();
        request.setProductKey(productkey);
        String param = "{\"params\":{\"Id\":\""+id+"\"},\"method\":\"thing.event.DeleteBoard.post\"}";
        request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
        request.setTopicFullName("/sys/"+productkey+"/"+devicename+"/thing/event/DeleteBoard/post");
        try
        {
            PubResponse response = client.getAcsResponse(request);
            if (response.getSuccess()==false){
                return new Response(CommonEnum.EVENT_PUB_FAIL);
            }

        }
        catch (ServerException e)
        {
            e.printStackTrace();
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response deletebox(String id) {
        String devicename = intelligentMonitorDao.getSmartByBoxid(id);
        intelligentMonitorDao.deletebBox(id);
        //删除格子信息订阅到iot
        IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PubRequest request = new PubRequest();
        request.setProductKey(productkey);
        String param = "{\"params\":{\"Id\":\""+id+"\"},\"method\":\"thing.event.DeleteBox.post\"}";
        request.setMessageContent(Base64.encodeBase64String(param.getBytes()));
        request.setTopicFullName("/sys/"+productkey+"/"+devicename+"/thing/event/DeleteBox/post");
        try
        {
            PubResponse response = client.getAcsResponse(request);
            if (response.getSuccess()==false){
                return new Response(CommonEnum.EVENT_PUB_FAIL);
            }

        }
        catch (ServerException e)
        {
            e.printStackTrace();
        }
        catch (ClientException e)
        {
            e.printStackTrace();
        }

        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response updateBox(int status, String boxonlyno) {

        intelligentMonitorDao.updateBoxStatus(status,boxonlyno);
        if (status==1||status==2) {
            intelligentMonitorDao.updateBoardStatus(0, boxonlyno);
        }
        if (status== 3) {
            intelligentMonitorDao.updateBoardStatus(1, boxonlyno);
            intelligentMonitorDao.updateSmartStatus(1,boxonlyno);
        }
        Response response = new Response();
        response.setOK();
        return response;
    }
}
